import socket
import threading
import time
import cv2
import requests
import numpy as np

token = "用户私钥"

# 上传图片到巴法云
def upload(image, message):
    url = "https://images.bemfa.com/upload/v1/upimages.php"
    headers = {
        "Content-Type": "image/jpg",
        "Authorization": token,
        "Authtopic": "snapshot",
        "wechatmsg": message
        }
    response = requests.post(url, headers = headers, data = image)
    print(response.json()["url"])
    response.close()


# 创建套接字
s = socket.socket()

# 连接服务器
s.connect(("bemfa.com", 8344))
server = s.makefile()

def heartbeat():
    while True:
        # 发送心跳消息
        s.sendall("ping\r\n".encode())
        print(server.readline())
        time.sleep(30)

# 创建心跳线程并启动
t = threading.Thread(target = heartbeat)
t.start()

# 订阅主题
cmd = "cmd=1&uid=" + token + "&topic=bell\r\n"
s.sendall(cmd.encode())
print(server.readline())

cam = cv2.VideoCapture(0)

while True:
    msg = server.readline()
    # 获取云端下发的信息中的最后两个字符，并删除结尾换行
    cmd = msg[-2:].strip()
    if cmd == "1":
        print("拍照")
        # 采集图像
        snapshot = cam.read()[1]
        # 压缩图像
        jpg = cv2.imencode(".jpg", snapshot)[1]
        data = np.array(jpg).tobytes()
        upload(data, "test")
